package cn.fulong.frame.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DicService {

    private Map<String, Map<String, String>> allDicData = new HashMap<>();  //key1=dic_type,key2=dic_code
    private Map<String, List<Map<String, Object>>> allDicList = new HashMap<>(); //key=dic_type

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //加载数据字典数据
    public List loadAllDic(String tableName) throws Exception {

        //sys_dic表
        List<Map<String, Object>> list =
                jdbcTemplate.queryForList("select dic_type,dic_code value,dic_value label from sys_dic order by dic_type,dic_code");
        String preDicType = "";
        Map<String, String> subDicData = new HashMap<>();
        List<Map<String, Object>> subDicList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map record = list.get(i);
            String dicType = record.get("dic_type").toString();
            String dicCode = record.get("value").toString();
            String dicValue = record.get("label").toString();

            if (i == 0) {
                preDicType = dicType;
            }
            if (!preDicType.equals(dicType)) {
                allDicData.put(preDicType, subDicData);
                allDicList.put(preDicType, subDicList);

                preDicType = dicType;
                subDicData = new HashMap<>();
                subDicList = new ArrayList<>();
            }
            subDicData.put(dicCode, dicValue);
            record.remove("dic_type");
            subDicList.add(record);
        }
        if (subDicData.size() > 0) {
            allDicData.put(preDicType, subDicData);
            allDicList.put(preDicType, subDicList);
        }

        System.out.println(allDicList.get(tableName));
        return allDicList.get(tableName);
    }

    //读取单个配置文件
    private List<String> readFile(String filename) {
        InputStream is = this.getClass().getResourceAsStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = "";
        List<String> lines = new ArrayList<>();
        int i = 0;
        try {
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }
}
